/*
-------------------------------------------------

	Sound.cpp

	Dmitriy Kuzmenko (Dgut)

-------------------------------------------------
*/

#include "Sound.h"
#include "OGG.h"

#ifdef WIN32
#include <windows.h>
#include <stdio.h>
#endif

namespace Autumn
{

/*
-------------------------------------------------

	Sound

-------------------------------------------------
*/

Sound::Sound( void ) :
	id	( 0 )
{
	alGenBuffers( 1, &id );
}

Sound::Sound( const OGG * ogg ) :
	id	( 0 )
{
	alGenBuffers( 1, &id );
	Init( ogg->GetChannels() == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, ogg->GetData(), ogg->GetSize(), ogg->GetRate() );
}

Sound::~Sound( void )
{
	alDeleteBuffers( 1, &id );
}

void Sound::Init( ALenum format, const ALvoid * data, ALsizei size, ALsizei frequency )
{
	alBufferData( id, format, data, size, frequency );
}

/*
-------------------------------------------------

	Stream

-------------------------------------------------
*/

Stream::Stream( OGG * ogg ) :
	current	( 0 ),
	ogg		( ogg )
{
}

Stream::~Stream( void )
{
	delete ogg;
}

const ALuint Stream::GetNextChunk( void )
{
	static char buffer[ STREAM_BUFFER_SIZE ];

	long size = ogg->Read( buffer, STREAM_BUFFER_SIZE );
	if( !size )
	{
		ogg->Rewind();
		size = ogg->Read( buffer, STREAM_BUFFER_SIZE );
	}

	const ALuint ID = sounds[ current ].GetID();

	sounds[ current ].Init( ogg->GetChannels() == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, buffer, size, ogg->GetRate() );
	current = ( current + 1 ) % STREAM_NUM_BUFFERS;

	return ID;
}

void Stream::Rewind( void )
{
	ogg->Rewind();
//	current = 0;
}

}	// namespace Autumn